/**
 * JAVACC DEMO 1.0
 */

package com.apache.rpc.common;

import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;

/**
 * description:  获取配置信息工具类
 *
 * @author ius 创建时间：2016-7-23
 */
public class RpcUtil {

    private static transient Map<String, Long> countMap = new HashMap<String, Long>(1);

    private static RpcUtil instance;

    private static transient String version = "";

    private RpcUtil() {
        filePath = ConfigUtil.getClassLoaderPath() + "config/";
    }

    public static RpcUtil getInstance() {
        if (null == instance) {
            instance = new RpcUtil();
        }
        return instance;
    }

    public static String getVersion() {
        return version;
    }

    public void setVersion(String rpcVersion) {
        if (StrUtil.isNotNull(rpcVersion)) {
            this.version = rpcVersion;
        }
    }

    /**
     * 判断对象是否为空
     *
     * @param obj 传入的对象
     * @return 如果obj为空返回true，不为空返回false
     */
    public static boolean isEmpty(Object obj) {
        return obj == null;
    }

    /**
     * 判断一个list集合是否为空
     *
     * @param list 传入的list
     * @return 如果list为空或者长度为0返回true，不为空返回false
     */
    public static boolean isEmpty(List list) { //
        return list == null || list.size() == 0;
    }

    /**
     * 判断一个list集合是否为空
     *
     * @param collection 传入的集合
     * @return 如果collection为空或者长度为0返回true，不为空返回false
     */
    public static boolean isEmpty(Collection collection) { //
        return collection == null || collection.isEmpty();
    }

    public long getCountMap(String key) {
        if (null == countMap.get(key))
            return 0;
        return countMap.get(key);
    }

    public void setCountMap(String key) {
        synchronized (countMap) {
            countMap.put(key, (countMap.get(key) + 1));
        }
    }

    public void delCountMap(String key) {
        synchronized (countMap) {
            if (null != countMap.get(key))
                countMap.put(key, (countMap.get(key) - 1));
        }
    }

    private Long lastUpateTime = 0l;//最后修改时间

    private Map<String, String> constant = new HashMap<String, String>(1);//存放系统配置参数

    private String filePath = "";

    /**
     * description: 加载配置文件
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private String initConfig(String key) {
        Properties prop = null;
        String fileName = "unity_config.properties";
        if (filePath.indexOf(".jar") != -1) {
            if (isEmpty(constant.get(fileName))) {
                prop = ConfigUtil.getInstance().getProperties(filePath, fileName);
            }
        } else {
            File oldfile = new File(filePath + fileName);
            if (oldfile.exists()) {
                long lastModletime = oldfile.lastModified();
                if (lastModletime > lastUpateTime) {//有更新从新加载
                    lastUpateTime = lastModletime;
                    prop = ConfigUtil.getInstance().getProperties(filePath + fileName);
                }
            }
        }
        if (null != prop) {
            Map<String, String> map = new HashMap<String, String>((Map) prop);
            Set propertySet = map.entrySet();
            for (Object o : propertySet) {
                Map.Entry entry = (Map.Entry) o;
                constant.put(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        if (ConfigUtil.isNull(key)) {
            return "";
        } else {
            return ConfigUtil.isNull(constant.get(key), "");
        }
    }

    /**
     * 获取property文件的属性值
     *
     * @param key
     * @return
     */
    public String getValueByKey(String key) {
        String result = initConfig(key);
        return result;
    }

    /**
     * 获取某个配置文件下的所有配置信息
     *
     * @return
     */
    public Map<String, String> getAllProperty() {
        return constant;
    }

    /**
     * 判断socket是否通
     */
    public boolean isHostConnectable(String host, String port) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(host, Integer.parseInt(port)), 100);
        } catch (IOException e) {
            return false;
        } finally {
            IOUtils.closeQuietly(socket);
        }
        return true;
    }

    public static void main(String args[]) {
        String str = "usage_patterns=0\n" + "#信息删除状态\n" + "INFO_DEL_STATUS=-1\n" + "#系统名称\n"
                + "sys_ename=rpc-server\n" + "#RPC系统超级用户(只能是一个,默认为admin)\n"
                + "console.user=admin\n";
        InputStream stream = null;
        try {
            stream = IOUtils.toInputStream(str);
            Properties prop = new Properties();
            prop.load(stream);
            Map<String, String> map = new HashMap<String, String>((Map) prop);
            System.out.println(map);
        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }
}
